<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入菜单名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="菜单类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择菜单类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_menu_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="显示状态" prop="visible">
        <el-select v-model="queryParams.visible" placeholder="请选择菜单显示状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_visible_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择菜单状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['system:menu:list']" type="primary" icon="el-icon-search" size="small"
                   @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['system:menu:add']" type="primary" plain icon="el-icon-plus" size="small"
                   @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="small" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
    </el-row>

    <el-table style="margin-top:20px" v-loading="loading" v-if="refreshTable" :data="menuList" row-key="id"
              :default-expand-all="isExpandAll" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true" width="150"/>
      <el-table-column prop="type" label="菜单类型" align="center" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type==='D'">目录</el-tag>
          <el-tag type="success" v-else-if="scope.row.type==='M'">菜单</el-tag>
          <el-tag type="info" v-else-if="scope.row.type==='B'">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="visible" label="显示状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_visible_status" :value="scope.row.visible"/>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="菜单状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.icon"/>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="permission" label="权限标识" :show-overflow-tooltip="true"/>
      <el-table-column align="center" prop="path" label="请求路径" :show-overflow-tooltip="true"/>
      <el-table-column align="center" prop="component" label="组件路径" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['system:menu:update']" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-hasPermi="['system:menu:add']" size="mini" type="text" icon="el-icon-plus"
                     @click="handleAdd(scope.row)">新增
          </el-button>
          <el-button v-hasPermi="['system:menu:delete']" size="mini" type="text" icon="el-icon-delete"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect v-model="form.parentId" :options="menuOptions" :normalizer="normalizer" :show-count="true"
                          placeholder="选择上级菜单"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="菜单类型" prop="type">
                <el-radio-group v-model="form.type">
                  <el-radio label="D">目录</el-radio>
                  <el-radio label="M">菜单</el-radio>
                  <el-radio label="B">按钮</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示排序">
                <el-input-number v-model="form.sort" controls-position="right" :min="1"/>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24" v-if="form.type !== 'B'">
            <el-form-item label="菜单图标" prop="icon">
              <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
                <IconSelect ref="iconSelect" @selected="selected"/>
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                  <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" class="el-input__icon"
                            style="height: 32px;width: 16px;"/>
                  <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜单名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 'B'">
            <el-form-item prop="path">
              <span slot="label">
                <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                路由地址
              </span>
              <el-input v-model="form.path" placeholder="请输入路由地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === 'M'">
            <el-form-item prop="component">
              <span slot="label">
                <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                组件路径
              </span>
              <el-input v-model="form.component" placeholder="请输入组件路径"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 'D'">
            <el-form-item>
              <el-input v-model="form.permission" placeholder="请输入权限标识" maxlength="100"/>
              <span slot="label">
                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                权限字符
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 'B'">
            <el-form-item label="显示状态" prop="visible">
              <el-radio-group v-model="form.visible">
                <el-radio
                  v-for="dict in dict.type.sys_visible_status"
                  :key="dict.value"
                  :label="Number(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 'B'">
            <el-form-item label="菜单状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="Number(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listMenu, getMenu, delMenu, addMenu, updateMenu} from "@/api/system/menu";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import IconSelect from "@/components/IconSelect";

  export default {
    name: "Menu",
    dicts: ['sys_menu_type', 'sys_visible_status', 'sys_common_status'],
    components: {
      Treeselect,
      IconSelect
    },
    data() {
      return {
        loading: true,
        // 菜单表格树数据
        menuList: [],
        // 菜单树选项
        menuOptions: [],
        queryParams: {
          name: '',
          type: ''
        },
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否展开，默认全部折叠
        isExpandAll: false,
        // 重新渲染表格状态
        refreshTable: true,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: {
            required: true,
            message: "菜单名称不能为空",
            trigger: "blur"
          },
          path: {
            required: true,
            message: "路由地址不能为空",
            trigger: "blur"
          }
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      /** 查询菜单列表 */
      getList() {
        this.loading = true;
        listMenu(this.queryParams).then(response => {
          this.menuList = response.data;
          this.menuOptions = response.data;
          this.loading = false;
        });
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          parentId: 0,
          name: undefined,
          icon: undefined,
          sort: 1,
          type: 'D',
          visible: 1,
          status: 1
        };
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.$refs['queryForm'].resetFields();
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        this.form.parentId = row && row.id ? row.id : 0
        this.title = "添加菜单";
        this.open = true;
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        getMenu(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改菜单";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.type == 'D') this.form.component = 'Layout'
            if (this.form.id !== undefined) {
              updateMenu(this.form).then(() => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addMenu(this.form).then(() => {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm(`此操作将删除【${row.name}】菜单, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delMenu(row.id).then(() => {
            this.getList();
            this.$message.success("删除成功");
          })
        }).catch(() => {
        });
      }
    }
  };
</script>
